package spring.cloud.tasks.executor.executor;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.common.Lifecycle;
import spring.cloud.tasks.executor.utils.log.LogEvents;
import spring.cloud.tasks.executor.utils.log.LogUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

@Slf4j
@Setter
@Getter
public class ExecutorResetCountService implements Lifecycle {
    private Timer timer;
    private ExecutorProcessCountResetTask executorProcessCountResetTask;

    public ExecutorResetCountService(String executorId) {
        timer = new Timer(executorId + "-reset-count-at-midnight");
        executorProcessCountResetTask = new ExecutorProcessCountResetTask(executorId);
    }

    // 每天临晨零点清理统计信息
    public void start() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0); // 凌晨0点
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date date = calendar.getTime();

        // 避免任务立即执行
        if (date.before(new Date())) {
            Calendar startDT = Calendar.getInstance();
            startDT.setTime(date);
            startDT.add(Calendar.DAY_OF_MONTH, 1);
            date = startDT.getTime();
        }
        timer.schedule(executorProcessCountResetTask, date, 24 * 60 * 60 * 1000L); // 时间间隔(一天)
        LogUtils.info(log, LogEvents.ExecutorEvent.INIT, "start the task of resetting statistics data");
    }

    public void stop() {
        timer.cancel();
    }
}
